import 'package:flutter/material.dart';
import '../base_notifier.dart';

// 状态构建器 Widget - 根据 BaseState 自动切换 UI
class StateBuilder<T> extends StatelessWidget {
  const StateBuilder({
    super.key,
    required this.state,
    required this.onSuccess,
    this.onLoading,
    this.onError,
    this.onEmpty,
    this.onIdle,
    this.showRefreshIndicator = true,
    this.errorRetryCallback,
  });

  /// 当前状态
  final BaseState<T> state;

  /// 成功状态的 Widget 构建器（必需）
  final Widget Function(T data) onSuccess;

  /// 加载状态的 Widget 构建器（可选，有默认实现）
  final Widget Function()? onLoading;

  /// 错误状态的 Widget 构建器（可选，有默认实现）
  final Widget Function(String error)? onError;

  /// 空数据状态的 Widget 构建器（可选，有默认实现）
  final Widget Function()? onEmpty;

  /// 空闲状态的 Widget 构建器（可选，有默认实现）
  final Widget Function()? onIdle;

  /// 是否显示刷新指示器
  final bool showRefreshIndicator;

  /// 错误重试回调
  final VoidCallback? errorRetryCallback;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _buildMainContent(),
        if (showRefreshIndicator && state.isRefreshing)
          const Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: LinearProgressIndicator(),
          ),
      ],
    );
  }

  Widget _buildMainContent() {
    // 加载中状态（非刷新状态）
    if (state.isLoading && !state.isRefreshing) {
      return onLoading?.call() ?? _defaultLoadingWidget();
    }

    // 错误状态（且没有数据时显示错误页面）
    if (state.isError && !state.hasData) {
      return onError?.call(state.error!) ?? _defaultErrorWidget(state.error!);
    }

    // 空数据状态
    if (state.isEmpty) {
      return onEmpty?.call() ?? _defaultEmptyWidget();
    }

    // 成功状态且有数据
    if (state.isSuccess && state.hasData) {
      return onSuccess(state.data!);
    }

    // 错误状态但有数据（显示数据，可以在顶部显示错误提示）
    if (state.isError && state.hasData) {
      return Column(
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            color: Colors.red.shade100,
            child: Row(
              children: [
                Icon(Icons.warning, color: Colors.red.shade700, size: 16),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    '操作失败: ${state.error}',
                    style: TextStyle(
                      color: Colors.red.shade700,
                      fontSize: 12,
                    ),
                  ),
                ),
                if (errorRetryCallback != null)
                  TextButton(
                    onPressed: errorRetryCallback,
                    child: const Text('重试', style: TextStyle(fontSize: 12)),
                  ),
              ],
            ),
          ),
          Expanded(child: onSuccess(state.data!)),
        ],
      );
    }

    // 空闲状态
    return onIdle?.call() ?? _defaultIdleWidget();
  }

  Widget _defaultLoadingWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('加载中...', style: TextStyle(color: Colors.grey)),
        ],
      ),
    );
  }

  Widget _defaultErrorWidget(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.error_outline, size: 64, color: Colors.red),
          const SizedBox(height: 16),
          Text(
            '出错了',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade800,
            ),
          ),
          const SizedBox(height: 8),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32),
            child: Text(
              error,
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.grey.shade600),
            ),
          ),
          const SizedBox(height: 24),
          if (errorRetryCallback != null)
            ElevatedButton.icon(
              onPressed: errorRetryCallback,
              icon: const Icon(Icons.refresh),
              label: const Text('重试'),
            ),
        ],
      ),
    );
  }

  Widget _defaultEmptyWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.inbox, size: 64, color: Colors.grey),
          SizedBox(height: 16),
          Text(
            '暂无数据',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.grey,
            ),
          ),
          SizedBox(height: 8),
          Text(
            '这里还没有任何内容',
            style: TextStyle(color: Colors.grey),
          ),
        ],
      ),
    );
  }

  Widget _defaultIdleWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.touch_app, size: 64, color: Colors.grey),
          SizedBox(height: 16),
          Text(
            '点击开始',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }
}

// 简化版状态构建器 - 只处理主要状态
class SimpleStateBuilder<T> extends StatelessWidget {
  const SimpleStateBuilder({
    super.key,
    required this.state,
    required this.onData,
    this.onRetry,
    this.loadingWidget,
    this.errorWidget,
    this.emptyWidget,
  });

  final BaseState<T> state;
  final Widget Function(T data) onData;
  final VoidCallback? onRetry;
  final Widget? loadingWidget;
  final Widget? errorWidget;
  final Widget? emptyWidget;

  @override
  Widget build(BuildContext context) {
    if (state.isLoading && !state.isRefreshing) {
      return loadingWidget ?? const Center(child: CircularProgressIndicator());
    }

    if (state.isError && !state.hasData) {
      return errorWidget ??
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.error, color: Colors.red),
                Text(state.error ?? '未知错误'),
                if (onRetry != null)
                  ElevatedButton(
                    onPressed: onRetry,
                    child: const Text('重试'),
                  ),
              ],
            ),
          );
    }

    if (state.isEmpty) {
      return emptyWidget ??
          const Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.inbox, color: Colors.grey),
                Text('暂无数据'),
              ],
            ),
          );
    }

    if (state.hasData) {
      return Column(
        children: [
          if (state.isRefreshing) const LinearProgressIndicator(),
          if (state.isError)
            Container(
              width: double.infinity,
              color: Colors.red.shade100,
              padding: const EdgeInsets.all(8),
              child: Text(
                '错误: ${state.error}',
                style: const TextStyle(color: Colors.red),
              ),
            ),
          Expanded(child: onData(state.data!)),
        ],
      );
    }

    return const SizedBox.shrink();
  }
}

// Riverpod 专用状态构建器
class RiverpodStateBuilder<T> extends StatelessWidget {
  const RiverpodStateBuilder({
    super.key,
    required this.state,
    required this.onData,
    this.onRetry,
    this.customLoadingWidget,
    this.customErrorWidget,
    this.customEmptyWidget,
  });

  final BaseState<T> state;
  final Widget Function(T data) onData;
  final VoidCallback? onRetry;
  final Widget? customLoadingWidget;
  final Widget? customErrorWidget;
  final Widget? customEmptyWidget;

  @override
  Widget build(BuildContext context) {
    return StateBuilder<T>(
      state: state,
      onSuccess: onData,
      onLoading: customLoadingWidget != null ? () => customLoadingWidget! : null,
      onError: customErrorWidget != null
          ? (_) => customErrorWidget!
          : null,
      onEmpty: customEmptyWidget != null ? () => customEmptyWidget! : null,
      errorRetryCallback: onRetry,
    );
  }
}